﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace MySSO.Core
{
    public class WebHelper
    {
        private readonly HttpContext _httpContext;

        public WebHelper()
        {
            this._httpContext = HttpContext.Current;

        }


        /// <summary>
        /// 获取当前ip
        /// </summary>
        /// <returns></returns>

        public virtual string GetCurrentIpAddress()
        {
            if (!IsRequestAvailable(_httpContext))
                return string.Empty;

            var result = "";
            if (_httpContext.Request.Headers != null)
            {

                var forwardedHttpHeader = "X-FORWARDED-FOR";

                //it's used for identifying the originating IP address of a client connecting to a web server
                //through an HTTP proxy or load balancer. 
                string xff = _httpContext.Request.Headers.AllKeys
                    .Where(x => forwardedHttpHeader.Equals(x, StringComparison.InvariantCultureIgnoreCase))
                    .Select(k => _httpContext.Request.Headers[k])
                    .FirstOrDefault();

                //if you want to exclude private IP addresses, then see http://stackoverflow.com/questions/2577496/how-can-i-get-the-clients-ip-address-in-asp-net-mvc
                if (!String.IsNullOrEmpty(xff))
                {
                    string lastIp = xff.Split(new char[] { ',' }).FirstOrDefault();
                    result = lastIp;
                }
                else
                {
                    var remoteHttpHeader = "REMOTE_ADDR";
                    string rm = _httpContext.Request.Headers.AllKeys
                 .Where(x => remoteHttpHeader.Equals(x, StringComparison.InvariantCultureIgnoreCase))
                 .Select(k => _httpContext.Request.Headers[k])
                 .FirstOrDefault();
                    if (!String.IsNullOrEmpty(rm))
                    {

                        result = rm.Split(new char[] { ',' }).FirstOrDefault();
                    }
                }
            }

            if (String.IsNullOrEmpty(result) && _httpContext.Request.UserHostAddress != null)
            {
                result = _httpContext.Request.UserHostAddress;
            }

            //some validation
            if (result == "::1")
                result = "127.0.0.1";
            //remove port
            if (!String.IsNullOrEmpty(result))
            {
                int index = result.IndexOf(":", StringComparison.InvariantCultureIgnoreCase);
                if (index > 0)
                    result = result.Substring(0, index);
            }

            return result;

        }

        /// <summary>
        /// 获取客户端详细信息
        /// </summary>
        /// <returns></returns>
        public string GetClientInfo()
        {
            try
            {
                return string.Empty;
                string osPat = "mozilla|m3gate|winwap|openwave|Windows NT|Windows 3.1|95|Blackcomb|98|ME|X Window|Longhorn|ubuntu|AIX|Linux|AmigaOS|BEOS|HP-UX|OpenBSD|FreeBSD|NetBSD|OS/2|OSF1|SUN";
                string info = "客户端的操作系统：" + _httpContext.Request.UserAgent;//获取操作系统
                string uAgent = _httpContext.Request.ServerVariables["HTTP_USER_AGENT"];
                //string machineName = Environment.MachineName;
                //string HostName = Dns.GetHostName();
                string HostName = System.Net.Dns.GetHostName();
                System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(osPat);
                info += "\r\n硬件：" + (reg.IsMatch(uAgent) ? "电脑" : "手机");//获取计算机还是手机
                info += "\r\nwin32系统：" + (_httpContext.Request.Browser.Win32 ? "是" : "否");
                info += "\r\n计算机名称：" + HostName;

                return info;
            }
            catch { }
            return string.Empty;
        }

        /// <summary>
        /// 判断支不支持cookie
        /// </summary>
        /// <returns></returns>
        public bool SupportCookies()
        {
            if (_httpContext.Request.Browser.Browser.Equals("Unknown", StringComparison.OrdinalIgnoreCase))//判断机器访问
                return false;
            if (!_httpContext.Request.Browser.Cookies)
                return false;

            return true;
        }

        /// <summary>
        /// 设置cookie
        /// </summary>
        /// <param name="cookiename"></param>
        /// <param name="cookievalue"></param>
        /// <param name="expires"></param>
        public void SetCookie(string cookiename, string cookievalue, DateTime expires)
        {
            HttpCookie cookie = new HttpCookie(cookiename, cookievalue);
            cookie.Expires = expires;
            _httpContext.Response.Cookies.Set(cookie);
        }

        /// <summary>
        /// 获取cookie
        /// </summary>
        /// <param name="cookiename"></param>
        /// <returns></returns>
        public string GetCookie(string cookiename)
        {
            HttpCookie cookie = _httpContext.Request.Cookies[cookiename];

            if (cookie == null)
            {
                return string.Empty;
            }
            else
            {
                return cookie.Value;
            }
        }

        /// <summary>
        /// 获取客户端简单信息
        /// </summary>
        /// <returns></returns>
        public string GetUserAgent()
        {
            string useragent = string.Empty;

            if (_httpContext.Request.ServerVariables != null)
            {
                useragent = _httpContext.Request.ServerVariables["HTTP_USER_AGENT"];
            }

            return useragent;
        }

        /// <summary>
        /// 获取浏览器信息
        /// </summary>
        /// <returns></returns>
        public string GetBrowser()
        {
            string browser = string.Empty;
            if (_httpContext.Request.Browser != null)
            {
                browser = _httpContext.Request.Browser.Browser + _httpContext.Request.Browser.Version;
            }

            return browser;

        }

        public string GetRequestUrl()
        {
            string refurl = string.Empty;
            if (_httpContext.Request.Url != null)
            {
                refurl = _httpContext.Request.Url.ToString();
            }

            return refurl;

        }

        /// <summary>
        /// 获取实际路径
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public string GetMapPath(string path)
        {
            if (_httpContext != null)
                return _httpContext.Server.MapPath(path);
            else
            {
                if (path.StartsWith("~/"))
                {
                    path = path.Substring(2);
                }
                else if (path.StartsWith("/"))
                {
                    path = path.Substring(1);
                }
                return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path.Replace('/', '\\'));
            }
        }


        public virtual bool IsStaticResource(HttpRequest request)
        {
            if (request == null)
                throw new ArgumentNullException("request");

            string path = request.Path;
            string extension = VirtualPathUtility.GetExtension(path);

            if (extension == null) return false;

            switch (extension.ToLower())
            {
                case ".axd":
                case ".ashx":
                case ".bmp":
                case ".css":
                case ".gif":
                case ".htm":
                case ".html":
                case ".ico":
                case ".jpeg":
                case ".jpg":
                case ".js":
                case ".png":
                case ".rar":
                case ".zip":
                    return true;
            }

            return false;
        }





        protected virtual Boolean IsRequestAvailable(HttpContext httpContext)
        {
            if (httpContext == null)
                return false;

            try
            {
                if (httpContext.Request == null)
                    return false;
            }
            catch (HttpException ex)
            {
                return false;
            }

            return true;
        }

    }
}
